﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StatusViewModel.cs" company="Spenta Consulting">
//   (c) Copyright 2011
// </copyright>
// <summary>
//   Defines the StatusViewModel type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Spenta.StreetCare.Silverlight.MVVM.ViewModels
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Windows.Browser;
    using System.Windows.Input;
    using GalaSoft.MvvmLight.Command;
    using GalaSoft.MvvmLight.Messaging;
    using Globals;
    using Logging;
    using Spenta.StreetCare.Silverlight.MVVM.Messages;
    using StreetCareAPI;

    /// <summary>
    /// Defines the StatusViewModel type.
    /// </summary>
    public class StatusViewModel : BaseViewModel
    {
        /// <summary>
        /// Private store for the list of statuses
        /// </summary>
        private IEnumerable<StatusWithCount> statusesWithCount;

        /// <summary>
        /// Initializes a new instance of the <see cref="StatusViewModel"/> class.
        /// </summary>
        public StatusViewModel()
        {
            if (HtmlPage.IsEnabled)
            {
                ApiClient.GetReportsCompleted += GetReportsCompleted;
                this.ApiClient.GetReportsByStatusCompleted += this.GetReportsByStatusCompleted;
                this.ApiClient.GetStatusesWithCountCompleted += this.GetStatusesWithCountCompleted;

                var customerID = Parameters.CustomerID;

                ApiClient.GetStatusesWithCountAsync(customerID);
                ApiClient.GetReportsAsync(customerID);

                Messenger.Default.Register<NewReportCompletedMessage>(this, this.NewReportCompleted);
            }
        }

        /// <summary>
        /// Gets the filter by status command.
        /// </summary>
        public ICommand FilterByStatusCommand
        {
            get
            {
                return new RelayCommand<int>(this.FilterByStatus);
            }
        }

        /// <summary>
        /// Gets or sets the statuses with count.
        /// </summary>
        /// <value>
        /// The statuses with count.
        /// </value>
        public IEnumerable<StatusWithCount> StatusesWithCount
        {
            get
            {
                return this.statusesWithCount;
            }

            set
            {
                this.statusesWithCount = value;
                RaisePropertyChanged("StatusesWithCount");
            }
        }

        /// <summary>
        /// Handles the new report completed event.
        /// </summary>
        /// <param name="message">The message.</param>
        public void NewReportCompleted(NewReportCompletedMessage message)
        {
            if (message.IsError)
            {
                return;
            }

            var report = message.Report;

            foreach (var element in
                this.statusesWithCount.Where(element => element.StatusID.Equals(report.ReportStatusID)))
            {
                element.ReportCount++;
            }
        }

        /// <summary>
        /// Filters the map pushpins by status id
        /// </summary>
        /// <param name="statusID">The status ID.</param>
        public void FilterByStatus(int statusID)
        {
            foreach (var element in this.statusesWithCount.Where(element => element.StatusID.Equals(statusID)))
            {
                element.IsDirty = true;
            }

            RaisePropertyChanged("StatusesWithCount");

            ApiClient.GetReportsByStatusAsync(statusID);
        }

        /// <summary>
        /// Gets the reports completed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Spenta.StreetCare.Silverlight.StreetCareAPI.GetReportsCompletedEventArgs"/> instance containing the event data.</param>
        private static void GetReportsCompleted(object sender, GetReportsCompletedEventArgs e)
        {
            try
            {
                if (e.Result.IsFault)
                {
                    LogHelper.Logger.WriteError("Error getting reports", e.Result.Fault.Exception);
                    return;
                }
            }
            catch (TargetInvocationException ex)
            {
                LogHelper.Logger.WriteError("Error getting reports", ex.InnerException ?? ex);
                return;
            }
            Messenger.Default.Send(e.Result.Reports);
        }

        /// <summary>
        /// Gets the reports by status completed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Spenta.StreetCare.Silverlight.StreetCareAPI.GetReportsByStatusCompletedEventArgs"/> instance containing the event data.</param>
        private void GetReportsByStatusCompleted(object sender, GetReportsByStatusCompletedEventArgs e)
        {
            try
            {
                if (e.Result.IsFault)
                {
                    LogHelper.Logger.WriteError("Error getting reports", e.Result.Fault.Exception);
                    return;
                }
            }
            catch (TargetInvocationException ex)
            {
                LogHelper.Logger.WriteError("Error getting reports", ex.InnerException ?? ex);
                return;
            }

            foreach (var element in this.statusesWithCount)
            {
                element.IsDirty = false;
            }

            Messenger.Default.Send(e.Result.Reports);
        }

        /// <summary>
        /// Gets the statuses with count completed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Spenta.StreetCare.Silverlight.StreetCareAPI.GetStatusesWithCountCompletedEventArgs"/> instance containing the event data.</param>
        private void GetStatusesWithCountCompleted(object sender, GetStatusesWithCountCompletedEventArgs e)
        {
            try
            {
                if (e.Result.IsFault)
                {
                    LogHelper.Logger.WriteError("Error getting statuses", e.Result.Fault.Exception);
                    return;
                }
            }
            catch (TargetInvocationException ex)
            {
                LogHelper.Logger.WriteError("Error getting statuses", ex.InnerException ?? ex);
                return;
            }
            this.StatusesWithCount = e.Result.StatusesWithCount;
        }
    }
}
